<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

            <el-form-item label="开始时间" style="width: 308px">
              <el-date-picker
                v-model="daterangeBeginDate"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="下单次数" prop="count">
              <el-input
                v-model="queryParams.count"
                placeholder="请输入下单次数"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="结束时间" style="width: 308px">
              <el-date-picker
                v-model="daterangeEndDate"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                  v-model="queryParams.status"
                  placeholder="请选择状态"
                  style="width: 180px"
                  clearable>
                <el-option
                  v-for="dict in in_use_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="用户id" prop="userId">
              <el-input
                v-model="queryParams.userId"
                placeholder="请输入用户id"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-card class="base-table" ref="fullTable">
            <TableSetup
                ref="tSetup"
                @onStripe="onStripe"
                @onRefresh="onRefresh"
                @onChange="onChange"
                @onfullTable="onfullTable"
                @onSearchChange="onSearchChange"
                :columns="columns"
                :isTable="isTable"
            >
                <template v-slot:operate>
                    <el-button
                      type="primary"
                      plain
                      icon="Plus"
                      @click="handleAdd"
                      v-hasPermi="['bg:vip:add']"
                    >新增</el-button>
                    <el-button
                      type="success"
                      plain
                      icon="Edit"
                      :disabled="single"
                      @click="handleUpdate"
                      v-hasPermi="['bg:vip:edit']"
                    >修改</el-button>
                    <el-button
                      type="danger"
                      plain
                      icon="Delete"
                      :disabled="multiple"
                      @click="handleDelete"
                      v-hasPermi="['bg:vip:remove']"
                    >删除</el-button>
                  <el-button
                        type="primary"
                        plain
                        icon="Upload"
                        @click="handleImport"
                        v-hasPermi="['bg:vip:import']"
                        >导入</el-button
                    >
                    <el-button
                      type="warning"
                      plain
                      icon="Download"
                      @click="handleExport"
                      v-hasPermi="['bg:vip:export']"
                    >导出</el-button>
                </template>
            </TableSetup>
            <auto-table
                ref="multipleTable"
                class="mytable"
                :tableData="vipList"
                :columns="columns"
                :loading="loading"
                :stripe="stripe"
                :tableHeight="tableHeight"
                @onColumnWidthChange="onColumnWidthChange"
                @onSelectionChange="handleSelectionChange"
            >

                    <template #beginDate="{ row }">
                      <span>{{ parseTime(row.beginDate, '{y}-{m}-{d}') }}</span>
                    </template>



                    <template #createTime="{ row }">
                      <span>{{ parseTime(row.createTime, '{y}-{m}-{d}') }}</span>
                    </template>



                    <template #endDate="{ row }">
                      <span>{{ parseTime(row.endDate, '{y}-{m}-{d}') }}</span>
                    </template>


                    <template #status="{ row }">
                        <dict-tag :options="in_use_status" :value="row.status"/>
                    </template>

                    <template #updateTime="{ row }">
                      <span>{{ parseTime(row.updateTime, '{y}-{m}-{d}') }}</span>
                    </template>

                <template #operate="{ row }">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['bg:vip:edit']">修改</el-button>
                  <el-button link type="primary" icon="Delete" @click="handleDelete(row)" v-hasPermi="['bg:vip:remove']">删除</el-button>
                </template>
            </auto-table>
            <div class="table-pagination">
                <pagination
                    v-show="total > 0"
                    :total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getList"
                />
            </div>
        </el-card>

    <!-- 添加或修改素材vip对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="vipRef" :model="form" :rules="rules" label-width="80px">

                <el-form-item label="开始时间" prop="beginDate">
                  <el-date-picker clearable
                    v-model="form.beginDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择开始时间">
                  </el-date-picker>
                </el-form-item>

                <el-form-item label="下单次数" prop="count">
                  <el-input v-model="form.count" placeholder="请输入下单次数" />
                </el-form-item>

                <el-form-item label="结束时间" prop="endDate">
                  <el-date-picker clearable
                    v-model="form.endDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择结束时间">
                  </el-date-picker>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择状态">
                    <el-option
                      v-for="dict in in_use_status"
                      :key="dict.value"
                      :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
      <!-- 导入数据对话框 -->
    <ImportData
        v-if="openImport"
        v-model="openImport"
        tableName="bg_vip"
        @success="handleImportSuccess"
    />
  </div>
</template>

<script setup name="BgVip">
import { listVip, getVip, delVip, addVip, updateVip, importVip } from "@/api/bg/vip";
import { listAllTable } from '@/api/system/table'
import TableSetup from '@/components/TableSetup'
import AutoTable from '@/components/AutoTable'
import ImportData from '@/components/ImportData'
const { proxy } = getCurrentInstance();
const { in_use_status } = proxy.useDict('in_use_status');

const vipList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
    const daterangeBeginDate = ref([]);
    const daterangeEndDate = ref([]);

const columns = ref([])
const stripe = ref(true)
const isTable = ref(true)
const tableHeight = ref(500)
const fullScreen = ref(false)
const openImport = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    beginDate: null,
    count: null,
    endDate: null,
    status: null,
    userId: null
  },
  rules: {
        beginDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],        count: [
          { required: true, message: "下单次数不能为空", trigger: "blur" }
        ],        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],        delFlag: [
          { required: true, message: "删除标志不能为空", trigger: "blur" }
        ],        deptId: [
          { required: true, message: "部门id不能为空", trigger: "blur" }
        ],        endDate: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询素材vip列表 */
function getList() {
  loading.value = true;
      queryParams.value.params = {};
      queryParams.value.params = {};
      if (null != daterangeBeginDate && '' != daterangeBeginDate) {
        queryParams.value.params["beginBeginDate"] = daterangeBeginDate.value[0];
        queryParams.value.params["endBeginDate"] = daterangeBeginDate.value[1];
      }
      if (null != daterangeEndDate && '' != daterangeEndDate) {
        queryParams.value.params["beginEndDate"] = daterangeEndDate.value[0];
        queryParams.value.params["endEndDate"] = daterangeEndDate.value[1];
      }
  listVip(queryParams.value).then(response => {
    vipList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getColumns() {
    listAllTable({ tableName: 'bg_vip' })
        .then((response) => {
            columns.value = response.data
        })
        .then(() => {
            getList()
        })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
        beginDate: null,        count: null,        createBy: null,        createTime: null,        delFlag: null,        deptId: null,        endDate: null,        id: null,        status: null,        updateTime: null,        userId: null  };
  proxy.resetForm("vipRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
      daterangeBeginDate.value = [];
      daterangeEndDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加素材vip";
}

/** 新增按钮操作 */
function handleImport() {
    openImport.value = true
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const bgVipId = row.id || ids.value
  getVip(bgVipId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改素材vip";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["vipRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateVip(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addVip(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除素材vip编号为"' + _ids + '"的数据项？').then(function() {
    return delVip(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('bg/vip/export', {
    ...queryParams.value
  }, `vip_${new Date().getTime()}.xlsx`)
}

//表格全屏
function onfullTable() {
    proxy.$refs.tSetup.onFull(proxy.$refs.fullTable.$el)
    fullScreen.value = !fullScreen.value
    updateTableHeight()
}
//表格刷新
function onRefresh() {
    getList()
}
//搜索框显示隐藏
function onSearchChange() {
    showSearch.value = !showSearch.value
}

function onStripe(val) {
    stripe.value = val
}
//改变表头数据
function onChange(val) {
    columns.value = val
}

//改变表格宽度
function onColumnWidthChange(column) {
    proxy.$refs.tSetup.tableWidth(column)
}

//更新表格高度
function updateTableHeight() {
    if (
        proxy.$refs.tSetup &&
        proxy.$refs.queryRef &&
        document.querySelector('.table-pagination')
    ) {
        if (fullScreen.value) {
            tableHeight.value = window.innerHeight - 145
        } else {
            tableHeight.value =
                window.innerHeight -
                proxy.$refs.tSetup.$el.clientHeight -
                proxy.$refs.queryRef.$el.clientHeight -
                document.querySelector('.table-pagination').clientHeight -
                220
        }
    }
}
//导入成功
function handleImportSuccess(sheetName, filedInfo, fileName) {
    let data = {
        tableName: 'bg_vip',
        filedInfo: filedInfo,
        fileName: fileName,
        sheetName: sheetName
    }
    importVip(data).then(() => {
        proxy.$modal.msgSuccess('导入成功')
        openImport.value = false
        getList()
    })
    getList()
}

onMounted(() => {
    updateTableHeight() // 初始化计算高度
    window.addEventListener('resize', updateTableHeight) // 监听窗口大小变化
})

onUnmounted(() => {
    window.removeEventListener('resize', updateTableHeight) // 销毁监听
})

getColumns()

</script>